package com.pinghua.mocha.basics;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangziyang
 * @since 2025/3/24
 */
public class List2MapKits {

    public static <K, V> Map<K, V> list2Map(List<V> list, String keyName, Class<V> cls) {
        Map<K, V> map = new HashMap<>(list.size());
        if (StrUtil.isBlank(keyName)) return map;
        keyName = upFirstChar(keyName);
        try {
            Method method = cls.getMethod(GET + keyName);
            method.setAccessible(true);
            for (V value : list) {
                K key = (K) method.invoke(value);
                map.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static <K, V, T>  Map<K, V> list2Map(List<T> list, String keyName, String valueName, Class<T> cls) {
        Map<K, V> map = new HashMap<>(list.size());
        if (CollectionUtil.isNotEmpty(list)) {
            keyName = upFirstChar(keyName);
            valueName = upFirstChar(valueName);
            try {
                Method kMethod = cls.getMethod(GET + keyName);
                Method vMethod = cls.getMethod(GET + valueName);
                kMethod.setAccessible(true);
                vMethod.setAccessible(true);
                K key;
                V value;
                for (T t : list) {
                    key = (K) kMethod.invoke(t);
                    value = (V) vMethod.invoke(t);
                    map.put(key, value);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    public static String upFirstChar(String source) {
        return source.substring(0, 1).toUpperCase() + source.substring(1);
    }

    public static final String GET = "get";
}
